﻿using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

public static class ConsulExtensions
{
    public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IConfiguration configuration)//, IHostApplicationLifetime lifetime)
    {
        var consulClient = new ConsulClient(c =>
        {
            c.Address = new Uri(configuration["ConsulSetting:ConsulAddress"]);
        });

        string httpCheck = $"https://{configuration["ConsulSetting:ServiceIP"]}:{configuration["ConsulSetting:ServicePort"]}{configuration["ConsulSetting:ServiceHealthCheck"]}";//健康检查地址

        Console.WriteLine(httpCheck);

        var registration = new AgentServiceRegistration()
        {
            ID = Guid.NewGuid().ToString(),//服务实例唯一标识
            Name = configuration["ConsulSetting:ServiceName"],//服务名
            Address = configuration["ConsulSetting:ServiceIP"], //服务IP
            Port = int.Parse(configuration["ConsulSetting:ServicePort"]),//服务端口 因为要运行多个实例，端口不能在appsettings.json里配置，在docker容器运行时传入
            Check = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册 秒
                Interval = TimeSpan.FromSeconds(5),//健康检查时间间隔 秒
                HTTP = httpCheck,//健康检查地址
                Timeout = TimeSpan.FromSeconds(5)//超时时间 秒
            }
        };


        //服务注册
        consulClient.Agent.ServiceRegister(registration).Wait();

        ////应用程序终止时，手动取消注册
        //lifetime.ApplicationStopping.Register(() =>
        //{
        //    consulClient.Agent.ServiceDeregister(registration.ID).Wait();
        //});

        return app;
    }


    public static void ConsulRegist(IConfiguration configuration)
    {
        try
        {
            string ip = configuration["ip"];
            string port = configuration["port"];
            string weight = configuration["weight"];
            string consulAddress = configuration["ConsulAddress"];
            string consulCenter = configuration["ConsulCenter"];

            ConsulClient client = new ConsulClient(c =>
            {
                c.Address = new Uri(consulAddress);
                c.Datacenter = consulCenter;
            });

            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID = "CommService" + Guid.NewGuid(),//--唯一的
                Name = "CommService",//分组---根据Service
                Address = ip,
                Port = int.Parse(port),
                Tags = new string[] { weight.ToString() },//额外标签信息
                                                          //Check = new AgentServiceCheck()
                                                          //{
                                                          //    Interval = TimeSpan.FromSeconds(12),
                                                          //    //HTTP = $"http://{ip}:{port}/Api/Health/Index", // 给到200


                //    HTTP = "https://10.10.50.99:5000/api/Book/GetInfo",

                //    Timeout = TimeSpan.FromSeconds(5),
                //    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)
                //}//配置心跳
            });
            Console.WriteLine($"{ip}:{port}--weight:{weight}"); //命令行参数获取
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Consul注册：{ex.Message}");
        }
    }

}
